<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <meta name="description" content="后台 | 后台管理系统 |joney"/>
    <meta name="author" content="joney"/>
    <title>后台管理系统</title>
    <link rel="stylesheet" type="text/css" th:href="@{/easyui/themes/black/easyui.css}" id="swicth-style"/>
    <link rel="stylesheet" type="text/css" th:href="@{/easyui/themes/icon.css}"/>
    <link rel="stylesheet" type="text/css" th:href="@{/css/common.css}"/>
    <script type="text/javascript" th:src="@{/js/jquery-1.8.0.min.js}"></script>
    <script type="text/javascript" th:src="@{/easyui/jquery.easyui.min.js}"></script>
    <script type="text/javascript" th:src="@{/easyui/locale/easyui-lang-zh_CN.js}"></script>
    <script type="text/javascript" th:src="@{/js/common.js}"></script>
    <script type="text/javascript" th:src="@{/js/easyui-validate.js}"></script>
    <style>
        #iconTb{
            margin: 5px;
            text-align: center;
            border-collapse: separate;
            border-spacing: 0px;
            border:0px;
            background-color: white;
        }
        #iconTb td{
            padding: 2px;
            border:1px solid #F4F4F4;
        }
        #iconTb td:hover{
            padding: 1px;
            border:1px solid red;
        }
        #viewTb{
            border-collapse: collapse;
            padding:1px;
            width: 100%;
        }

        #viewTb,#viewTb tr th, #viewTb tr td {
            border:1px solid #EFEFEF;
        }
    </style>
</head>

<body>
    <div style="width: 400px;float: left">
        <div style="margin-bottom: 10px">
            <select class="easyui-combobox" id="category_sch" style="width:120px"
                    data-options="editable:false,panelHeight:'auto',onChange:function(n,o){changeCategory(n,o);}">
                <option value="0" selected="selected">所有资源</option>
                <option value="1">左侧菜单栏</option>
            </select>
            <span class="easyui-linkbutton" iconCls="icon-tip">提示: 在树上点击右键操作</span>
        </div>
        <ul id="resTree"></ul>
    </div>
    <div id="viewPanel" style="float: left;display: none;">
        <div th:include="sys_base/res_view :: viewFrag"  class="easyui-panel" title="资源详情" style="width:400px"/>
    </div>
    <div id="mm" class="easyui-menu" style="width:120px;">
        <div onclick="viewit()" id="item_view" data-options="iconCls:'icon-more'">查看</div>
        <div th:if="${authMap.canEdit}" onclick="eidtit()" id="item_eidtit" data-options="iconCls:'icon-edit'">编辑当前</div>
        <div th:if="${authMap.canAdd}" onclick="append()" id="item_append" data-options="iconCls:'icon-add'">添加子节点</div>
        <div onclick="refreshTree()" data-options="iconCls:'icon-reload'">刷新导航树</div>
        <div class="menu-sep"></div>
        <div th:if="${authMap.canDel}" onclick="removeit()" id="item_removeit" data-options="iconCls:'icon-remove'">删除当前</div>
        <div th:if="${authMap.canDel}" onclick="removeitbatch()" id="item_removeitbatch" data-options="iconCls:'icon-delete'">删除勾选</div>
        <div th:if="${authMap.canDel}" class="menu-sep"></div>
        <div onclick="expand()">展开</div>
        <div onclick="collapse()">收起</div>
    </div>

    <div id="addDlg" class="easyui-dialog" title="新增" style="width:400px;height:430px;padding:10px"
         data-options="modal:true,closed:true,
                cache: false,
				iconCls: 'icon-save',
				onClose : function() {
                    resetAddForm();
                },
				buttons: [{
					text:'保存',
					iconCls:'icon-ok',
					handler:function(){
						saveAddForm();
					}
				},{
					text:'取消',
					iconCls:'icon-cancel',
					handler:function(){
					    resetAddForm();
						$('#addDlg').dialog('close');
					}
				}]
			">
        <div th:include="sys_base/res_add :: addFrag"></div>
    </div>

 <script th:inline="javascript">
/*<![CDATA[*/
    var canAdd = /*[[${authMap.canAdd}]]*/ false;
    var canEdit = /*[[${authMap.canEdit}]]*/ false;
    var canDel = /*[[${authMap.canDel}]]*/ false;
$(function(){
    $('#resTree').tree({
        url: "/res/tree",
        method: 'get',
        checkbox:true,
        lines:true,
        animate: true,
        onlyLeafCheck:true,
        dnd:canEdit,
        loadFilter: function(data){
            //alert("--------:"+JSON.stringify(data));
            return data;
        /*            if(data instanceof Array){*/
        },
        onLoadError:function(error){
            showMsg('加载数据失败11');
        },
        onDblClick:function (node) {
            $(this).tree(node.state == 'closed' ? 'expand' : 'collapse', node.target);
        },
        onContextMenu: function(e,node){
            e.preventDefault();
            $(this).tree('select',node.target);
            var category = $("#category_sch").combobox('getValue');
            if(category==1){ //左侧菜单栏
                if(node.level==3){
                    $('#mm').menu('disableItem', $('#item_append'));
                    $('#mm').menu('enableItem', $('#item_eidtit'));
                }else if(node.level==1){
                    $('#mm').menu('disableItem', $('#item_eidtit'));
                }else{
                    $('#mm').menu('enableItem', $('#item_append'));
                    $('#mm').menu('enableItem', $('#item_eidtit'));
                }
            }
            if(node.pid==0){
                $('#mm').menu('disableItem', $('#item_eidtit'));
                $('#mm').menu('disableItem', $('#item_removeit'));
                $('#mm').menu('disableItem', $('#item_removeitbatch'));
            }else{
                $('#mm').menu('enableItem', $('#item_eidtit'));
                $('#mm').menu('enableItem', $('#item_removeit'));
                $('#mm').menu('enableItem', $('#item_removeitbatch'));
            }

            $('#mm').menu('show',{
                left: e.pageX,
                top: e.pageY
            });
        },
        //onBeforeLoad:function (node, param) {
        //},
        onBeforeDrag:function (node) {
            if(node.level==1){ //第二层的不允移动
                return false;
            }
        },
        onDragEnter:function (target, source) { //进入目标节点
            var category = $("#category_sch").combobox('getValue');
            var targetNode = $(this).tree('getNode',target);
           //console.log(targetNode.pid+"---"+source.pid);
            if(category==1 && targetNode.level==3){
                return false;
            }
            if(targetNode.id==source.pid){
                return false;
            }
        },
        //onDragOver:function (target, source) { //在目标节点上划动
        //},

        //onDragLeave:function (target, source) { //离开目标节点
        //},

        onBeforeDrop:function (target, source,point) { //开始释放前
            if(point!="append"){
                return false;
            }
            $.messager.progress();
            var targetNode = $(this).tree('getNode',target);
            var flag = false;
            $.ajax({
                type:'GET',
                contentType: "application/json; charset=utf-8",
                url:"/res/move?pid="+targetNode.id+"&id="+source.id,
                cache:false,
                async:false,
                dataType:'json',
                success:function(data){
                    if(data.code!=0){
                        $.messager.alert('提示', data.msg, 'error');
                    }else{
                        showMsg('移动成功');
                        flag = true;
                    }
                },
                error:function(e) {
                    $.messager.alert('提示', '移动失败', 'error');

                },
                complete:function () {
                    $.messager.progress('close');
                }
            });

            return flag;
        },
        onDrop:function (target, source,point) { //释放中
            $('#resTree').tree('reload');
        }

    });
})

    function viewit() {
        var node = $('#resTree').tree('getSelected');
        $.messager.progress();
        $.ajax({
            type:'GET',
            contentType: "application/json; charset=utf-8",
            url:"/res/detail?id="+node.id,
            cache:false,
            dataType:'json',
            success:function(data){
                if(data.code!=0){
                    $.messager.alert('提示', data.msg, 'error');
                }else{

                    $("#viewPanel").show();
                    $("#span_name").html(data.data.node.name);
                    $("#span_parentNodeName").html(data.data.parentNode == null ?"":data.data.parentNode.name);
                    $("#span_url").html(data.data.node.url);
                    if(data.data.node.icon){
                        $("#img_icon_view").show();
                        $("#img_icon_view").attr("src","/easyui/themes/myicons/"+data.data.node.icon);
                    }else{
                        $("#img_icon_view").hide();
                    }
                    $("#span_permission").html(data.data.node.permission);
                    $("#span_seq").html(data.data.node.seq);
                    $("#span_method").html(data.data.node.method=="NONE"?"":data.data.node.method);
                    var resType=data.data.node.resType;
                    if(resType=="AUTH"){
                        resType="权限";
                    }else if(resType=="API"){
                        resType="API";
                    }else if(resType=="MENU"){
                        resType="子菜单";
                    }else if(resType=="FOLDER"){
                        resType="菜单夹";
                    }
                    $("#span_resType").html(resType);
                    $("#span_state").html(data.data.node.state==1?"启用":"禁用");
                    $("#span_createTime").html(timeStamp2String(data.data.node.createTime));
                    $("#span_createUser").html(data.data.node.createUser);

                    if(data.data.roleList != null){
                        var roles = new Array();
                        $.each(data.data.roleList, function (index, item) {
                            roles.push(item.name);
                        })
                        $("#span_roles").html(roles.join("、"));
                    }
                }
            },
            error:function(e) {
                $.messager.alert('提示', '删除失败', 'error');

            },
            complete:function () {
                $.messager.progress('close');
            }
        });
    }
    function append(){
        var node = $('#resTree').tree('getSelected');
        $('#addDlg').dialog('open');
        $("input[name='parentId']").val(node.id);
        $("input[name='parentNodeName']").val(node.text);
/*        t.tree('append', {
            parent: (node?node.target:null),
            data: [{
                id:10000001,
                text: 'new item1'
            },{
                id:1000002,
                text: 'new item2'
            }]
        });*/
    }
    
    function eidtit() {
        var node = $('#resTree').tree('getSelected');
        $('<div></div>').dialog({
            id : 'editDlg',
            iconCls: 'icon-edit',
            title : '编辑',
            width : 400,
            height : 430,
            closed : false,
            cache : false,
            href : '/res/edit?id='+node.id,
            modal : true,
            onClose : function() {
                $(this).dialog('destroy');
            },
            onLoad:function (data) {
                var resType = $("#combobox_resType").combobox('getValue');
                var box = $("input[name='url']");
                var box2 = $("input[name='permission']");

                if(resType=='FOLDER' || resType=='MENU'){
                    $("#editForm").find("#selectIconRow").show();
                }

                if(resType=='FOLDER' || resType=="AUTH"){
                    box.val("");
                    box.validatebox({
                        required:false,
                        disabled:true
                    });
                    box2.validatebox({
                        required:true,
                        disabled:false
                    });
                }else if(resType=='MENU'){
                    box2.validatebox({
                        required:true,
                        disabled:false
                    });
                }else{
                    box.validatebox({
                        required:true,
                        disabled:false
                    });
                    box2.val("");
                    box2.validatebox({
                        required:false,
                        disabled:true
                    });
                }
            },
            buttons : [ {
                text : '保存',
                iconCls : 'icon-ok',
                handler : function() {
                    //提交表单
                    updateForm();
                }
            }, {
                text : '取消',
                iconCls : 'icon-cancel',
                handler : function() {
                    $("#editDlg").dialog('destroy');
                }
            } ]
        });
    }
    function removeit(){
        var node = $('#resTree').tree('getSelected');
        if(node.pid==0 ||node.pid==1000){
            $.messager.alert('提示', "\<br\/\>系统基础菜单不可以删除！", 'error');
            return;
        }
        doDelete(new Array(node));
    }

    function removeitbatch(){
        var nodes = $('#resTree').tree('getChecked');
        doDelete(nodes);
    }
    
    function doDelete(nodes) {
        if(nodes.length==0){
            showMsg('请先勾选一条记录');
            return;
        }
        var ids=[];
        var texts=[];
        var stopSubmit = false;
        for(var i=0; i<nodes.length; i++){
            if(nodes[i].pid==0 ||nodes[i].pid==1000){
                $.messager.alert('提示', "\<br\/\>系统基础菜单不可以删除！", 'error');
                stopSubmit = true;
                break;
            }
            ids.push(nodes[i].id);
            texts.push(nodes[i].text);
        }
        if(stopSubmit){
            return;
        }
        $.messager.confirm({
            width: 350,
            title: '提示',
            msg: '确认要删除以下节点吗?\<br\/\>\<span style=\"color: blue\"\>【'+texts.join("、")+'】\<\/span\>',
            ok: "是",
            cancel: "否",
            fn: function (r) {
                if (r){
                    $.messager.progress();
                    $.ajax({
                        type:'GET',
                        contentType: "application/json; charset=utf-8",
                        url:"/res/remove?ids="+ids.join("-"),
                        cache:false,
                        dataType:'json',
                        success:function(data){
                            if(data.code!=0){
                                $.messager.alert('提示', data.msg, 'error');
                            }else{
                                showMsg('删除成功');
                                for(var i=0; i<nodes.length; i++){
                                    $('#resTree').tree('remove', nodes[i].target);
                                }
                            }
                        },
                        error:function(e) {
                            $.messager.alert('提示', '删除失败', 'error');

                        },
                        complete:function () {
                            $.messager.progress('close');
                        }
                    });
                }
            }
        });
    }
    function collapse(){
        var node = $('#resTree').tree('getSelected');
        $('#resTree').tree('collapse',node.target);
    }
    function expand(){
        var node = $('#resTree').tree('getSelected');
        $('#resTree').tree('expand',node.target);
    }
    
    function refreshTree() {
       // var params = {
       //     roleId: selected.Id,
       //     roleName: selected.Name
       // };
       // $('#resTree').tree("options").queryParams = params;
        $('#resTree').tree('reload');
        $('#viewPanel').hide();
    }
    //保存表单
    function saveAddForm() {

        if($('#addForm').form('validate')){
           // alert($('#addForm').serializeJSON());
            $.messager.progress();
            $.ajax({
                type:'POST',
                contentType: "application/json; charset=utf-8",
                url:"/res/insert",
                data:$('#addForm').serializeJSON(),
                cache:false,
                dataType:'json',
                success:function(data){
                    if(data.code!=0){
                        $.messager.alert('提示', data.msg, 'error');
                    }else{
                        showMsg('添加成功');
                        //var node = $('#resTree').tree('getSelected');
                        //alert(JSON.stringify(node));
                        resetAddForm();
                        $('#addDlg').dialog('close');
                        $('#resTree').tree('append', {
                            parent: $('#resTree').tree('getSelected').target,
                            data:data.data
                        });
                    }
                },
                error:function(e) {
                    $.messager.alert('提示', '提交失败', 'error');

                },
                complete:function () {
                    $.messager.progress('close');
                }
            });
        }
    }
    
    function updateForm() {
        if($('#editForm').form('validate')){
            $.messager.progress();
            $.ajax({
                type:'POST',
                contentType: "application/json; charset=utf-8",
                url:"/res/update",
                data:$('#editForm').serializeJSON(),
                cache:false,
                dataType:'json',
                success:function(data){
                    if(data.code!=0){
                        $.messager.alert('提示', data.msg, 'error');
                    }else{
                        showMsg('提交成功');
                        $("#editDlg").dialog('destroy');
                        refreshTree();
                    }
                },
                error:function(e) {
                    $.messager.alert('提示', '提交失败', 'error');

                },
                complete:function () {
                    $.messager.progress('close');
                }
            });
        }
    }
    function changeCategory(n,o) {
         var params = {
             filterId: n,
         };
         $('#resTree').tree("options").queryParams = params;
         $('#resTree').tree('reload');
         $('#viewPanel').hide();
    }
    function resTypeChange(n,o,formId) {
        var box = $("input[name='url']");
        var box2 = $("input[name='permission']");

        if((o!='FOLDER' || o!='MENU') && (n=='FOLDER' || n=='MENU')){
            $("#"+formId).find("#selectIconRow").show();
            var s = $("#"+formId).find("#img_icon").attr("src");
            if(s.length>0){
                $("#"+formId).find('#searchbox_icon').searchbox("setValue",s.substring(s.lastIndexOf("/")+1));
            }
        }else{
            $("#"+formId).find("#selectIconRow").hide();
            $("#"+formId).find('#searchbox_icon').searchbox("setValue","");
        }
        if(n=='FOLDER' || n=="AUTH"){
            box.val("");
            box.validatebox({
                required:false,
                disabled:true
            });
            box2.validatebox({
                required:true,
                disabled:false
            });
        }else if(n=='MENU'){
            box.validatebox({
                required:true,
                disabled:false
            });
            box2.validatebox({
                required:true,
                disabled:false
            });
        }else{
            box.validatebox({
                required:true,
                disabled:false
            });
            box2.val("");
            box2.validatebox({
                required:false,
                disabled:true
            });
        }
    }
    function resetAddForm() {
        $('#addForm').form('reset');
        $("input[name='url']").validatebox({
            required:false,
            disabled:true
        });
        $("input[name='permission']").validatebox({
            required:true,
            disabled:false
        });
        $("#addDlg").find("#img_icon").hide();
        $("#addDlg").find("#searchbox_icon").searchbox("setValue","");
    }

    function selectIcon(value,name) {
        $('<div></div>').dialog({
            id : 'selectIconDlg',
            iconCls: 'icon-search',
            title : '选择图标',
            width : 700,
            height : 400,
            closed : false,
            cache : false,
            href : '/icons.json',
            modal : true,
            onClose : function() {
                $(this).dialog('destroy');
            },
            onLoad:function (data) {
                //var arr=JSON.parse(data);
                $("#selectIconDlg").empty();
                $("#selectIconDlg").append("\<table\ id='iconTb'>\<\/table\>");
                var tr="";
                var img="";
                $.each(JSON.parse(data), function (index, item) {
                    img="<img src='"+item.url+"' width='"+item.width+"' height='"+item.height+"' title='"+item.title+"'\/>";
                    if((index+1)%30==0 && tr!="" ){ //换一行
                        tr+="\<td\ onclick='choseMe(this)'>"+img+"\<\/td\>";
                        $("#iconTb").append("\<tr\>"+tr+"\<\/tr\>");
                        tr="";
                    }else{
                        tr+="\<td\ onclick='choseMe(this)'>"+img+"\<\/td\>";
                    }
                });
            },
            buttons : [{
                text : '关闭',
                iconCls : 'icon-cancel',
                handler : function() {
                    $("#selectIconDlg").dialog('destroy');
                }
            } ]
        });
    }

    function choseMe(obj) {
        var img = $(obj).find("img");
        if($("#editDlg").length > 0){
            $("#editDlg").find("#img_icon").attr("src",img.attr("src"));
            $("#editDlg").find("#img_icon").show();
            $("#editDlg").find("#searchbox_icon").searchbox("setValue",img.attr("title"));
        }else{
            $("#addDlg").find("#img_icon").attr("src",img.attr("src"));
            $("#addDlg").find("#img_icon").show();
            $("#addDlg").find("#searchbox_icon").searchbox("setValue",img.attr("title"));
        }
        $("#selectIconDlg").dialog('destroy');
    }
/*]]>*/
</script>
</body>
</html>